﻿

//ftp类
using System;
using System.Text;
using System.Net;
using System.IO;

namespace RevitAddInDeployer
{
    public class FtpHelper
    {
        //基本设置
        static public string path = @"ftp://" + "8.142.144.242/family/" ;    //目标路径
        static public string ftpip = "192.168.1.103";    //ftp IP地址
        static public string username = "ftpuser";   //ftp用户名
        static public string password = "1qazZSE$";   //ftp密码
        static public string uploadpath = @"ftp://" + "8.142.144.242" + "/upload";    //目标路径
        /// <summary>
        /// 单个文件下载方法
        /// </summary>
        /// <param name="adss">保存文件的本地路径</param>
        /// <param name="ftpadss">下载文件的FTP路径</param>
        public static void Download(string adss, string ftpadss)
        {
            try
            {
                //FileMode常数确定如何打开或创建文件,指定操作系统应创建新文件。
                //FileMode.Create如果文件已存在，它将被改写
                FileStream outputStream = new FileStream(adss, FileMode.Create);
                FtpWebRequest downRequest = (FtpWebRequest)WebRequest.Create(new Uri(ftpadss));
                downRequest.Credentials = new NetworkCredential(username, password);
                //设置要发送到 FTP 服务器的命令
                downRequest.Method = WebRequestMethods.Ftp.DownloadFile;
                FtpWebResponse response = (FtpWebResponse)downRequest.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                long cl = response.ContentLength;
                int bufferSize = 2048;
                int readCount;
                byte[] buffer = new byte[bufferSize];
                readCount = ftpStream.Read(buffer, 0, bufferSize);
                while (readCount > 0)
                {
                    outputStream.Write(buffer, 0, readCount);
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                }
                ftpStream.Close();
                outputStream.Close();
                response.Close();
            }
            catch(Exception e) {
               
            }
        }

        /// </summary>
        /// <param name="ftpads">FTP地址路径</param>
        /// <param name="name">我们所选择的文件或者文件夹名字</param>
        /// <param name="type">要发送到FTP服务器的命令</param>
        /// <returns></returns>
        public static  string[] ftp(string ftpads, string name, string type)
        {
            WebResponse webresp = null;
            StreamReader ftpFileListReader = null;
            FtpWebRequest ftpRequest = null;
            try
            {
                ftpRequest = (FtpWebRequest)WebRequest.Create(new Uri(ftpads + name));
                ftpRequest.Credentials = new NetworkCredential(username, password);
                
                ftpRequest.Method = type;
                webresp = ftpRequest.GetResponse();
                ftpFileListReader = new StreamReader(webresp.GetResponseStream(), Encoding.UTF8);
            }
            catch (Exception ex)
            {
                ex.ToString();

            }
            StringBuilder str = new StringBuilder();
            string line = ftpFileListReader.ReadLine();
            while (line != null)
            {
                str.Append(line);
                str.Append("\n");
                line = ftpFileListReader.ReadLine();
            }
            string[] fen = str.ToString().Split('\n');
            return fen;
        }

        /// <summary>
        /// 下载方法KO
        /// </summary>
        /// <param name="ftpads">FTP路径</param>
        /// <param name="name">需要下载文件路径</param>
        /// <param name="Myads">保存的本地路径</param>
        public static void Downftp(string ftpads, string name, string Myads)
        {
          
            //判断文件夹是否存在
            if (!Directory.Exists(Myads))
            {
                //创建文件夹
                
                    Directory.CreateDirectory(Myads);
               
            }
            string downloadDir = Myads + name;
            string ftpdir = ftpads + name;
            string[] fullname = ftp(ftpads, name, WebRequestMethods.Ftp.ListDirectoryDetails);
            //判断是否为单个文件 
            if (fullname.Length <= 2) 
            {
                if (fullname[fullname.Length - 1] == "")
                {
                    Download(downloadDir + "/" + name, ftpads + name + "/" + name);
                }
            }
            else
            {
                string[] onlyname = ftp(ftpads, name, WebRequestMethods.Ftp.ListDirectory);
                if (!Directory.Exists(downloadDir))
                {
                    Directory.CreateDirectory(downloadDir);
                }
                foreach (string names in fullname)
                {
                    //判断是否具有文件夹标识<DIR>
                    if (names.Contains("drwxr-xr-x"))
                    {
                        int b = names.LastIndexOf(" ") + 1;
                        int c = names.Length;
                        string olname = names.Substring(b, c - b).Trim();
                        Downftp(ftpdir, "\\" + olname, downloadDir);
                    }
                    else
                    {
                        foreach (string onlynames in onlyname)
                        {
                            if (onlynames.Contains(".rfa") || onlynames.Contains(".rvt") || onlynames =="")
                            {
                                continue;
                            }
                            else
                            {
                                int d = onlynames.LastIndexOf("/") + 1;
                                int e = onlynames.Length;
                                string filename= onlynames.Substring(d, e - d);
                                if (names.Contains(filename))
                                {
                                    Download(downloadDir + "\\" + filename, ftpads + name + "\\" + filename);
                                    break;
                                }
                            }
                        }
                    }
                }
            }

        } 

        /// <summary>  
        /// 上传  
        /// </summary>   
        public static void Upload(string srcFilename, string destFtp,string usernames, bool enalbeSsl = false)
        {
            FileInfo fileInf = new FileInfo(srcFilename);
            string legalDestFtp = getLegalName(destFtp);
            
            if (!DirectoryExist(usernames))
            {
                //创建文件夹
                MakeDir(usernames);

            }
            FtpWebRequest reqFTP = (FtpWebRequest)WebRequest.Create(new Uri(uploadpath +"/"+ usernames + "/"+ legalDestFtp +".rfa"));
            reqFTP.Credentials = new NetworkCredential(username, password);
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
            reqFTP.KeepAlive = false;
            reqFTP.UseBinary = true;
            reqFTP.ContentLength = fileInf.Length;
            reqFTP.EnableSsl = enalbeSsl;


            int buffLength = 2048;
            byte[] buff = new byte[buffLength];
            int contentLen;
            try
            {
                using (FileStream fs = fileInf.OpenRead())
                {
                    using (Stream strm = reqFTP.GetRequestStream())
                    {
                        contentLen = fs.Read(buff, 0, buffLength);
                        while (contentLen != 0)
                        {
                            strm.Write(buff, 0, contentLen);
                            contentLen = fs.Read(buff, 0, buffLength);
                        }
                        strm.Close();
                        fs.Close();
                    }
                }
            }
            catch (WebException ex)
            {
                throw ex;
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        private static string getLegalName(string name)
        {
            return name.Replace("#", "%23").Replace("&", "%26").
                Replace("=", "%3D").Replace("?", "%25")
                .Replace("+", "%2B").Replace(" ", "%20").Replace("/", "%2F");
        }

        /// <summary>
        /// 判断当前目录下指定的子目录是否存在
        /// </summary>
        /// <param name="RemoteDirectoryName">指定的目录名</param>
        public static bool DirectoryExist(string RemoteDirectoryName)
        {
            string[] dirList = GetDirectoryList();
            foreach (string str in dirList)
            {
                if (str.Trim() == RemoteDirectoryName.Trim())
                {
                    return true;
                }
            }
            return false;
        }


        /// <summary>
        /// 获取当前目录下所有的文件夹列表(仅文件夹)
        /// </summary>
   /// <returns></returns>
        public static string[] GetDirectoryList()
        {
            string[] drectory = GetFilesDetailList();
            string m = string.Empty;
            foreach (string str in drectory)
            {
                //if (str.Trim().Substring(0, 1).ToUpper() == "D")
                //{
                    m += str.Substring(30).Trim() + "\n";
                //}
            }

            char[] n = new char[] { '\n' };
            return m.Split(n);
        }

        /// <summary>
        /// 获取当前目录下明细(包含文件和文件夹)
        /// </summary>
        /// <returns></returns>
        public static string[] GetFilesDetailList()
        {
            string[] downloadFiles;
            try
            {
                StringBuilder result = new StringBuilder();
                FtpWebRequest ftp;
                ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(uploadpath));
                ftp.Credentials = new NetworkCredential(username, password);
                ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                WebResponse response = ftp.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());
                string line = reader.ReadLine();
                //line = reader.ReadLine();
                //line = reader.ReadLine();
                while (line != null)
                {
                  
                    result.Append(line);
                    result.Append("\n");
                    line = reader.ReadLine();
                }
                result.Remove(result.ToString().LastIndexOf("\n"), 1);
                
                reader.Close();
                   response.Close();
               
                return result.ToString().Split('\n');
               
            }
            catch (Exception ex)
            {
                downloadFiles = null;
                Insert_Standard_ErrorLog.Insert("FtpWeb", "GetFilesDetailList Error --> " + ex.Message);
                return downloadFiles;
            }
        }


        /// <summary>
        /// 创建文件夹
        /// </summary>
        /// <param name="dirName"></param>
        public static void MakeDir(string dirName)
        {
            FtpWebRequest reqFTP;
            try
            {
                // dirName = name of the directory to create.
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uploadpath +"/"+dirName));
                reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(username, password);
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();

                ftpStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                Insert_Standard_ErrorLog.Insert("FtpWeb", "MakeDir Error --> " + ex.Message);
            }
        }
        public static class Insert_Standard_ErrorLog
        {
            public static void Insert(string x, string y)
            {

            }
        }

    }
}
